package com.kingzoder.food.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.kingzoder.food.common.CommonConstant;
import com.kingzoder.food.common.base.BaseDO;
import com.kingzoder.food.common.base.LogicDO;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;
import java.util.Objects;

/**
 * @author 轩辕铮
 * @Description: 数据库默认字段填充
 **/
public class DefaultFieldHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.getOriginalObject() instanceof BaseDO) {
            BaseDO baseDO = (BaseDO) metaObject.getOriginalObject();
            Date current = new Date();
            Long userID = -1L;
//todo            try {
//                 userID = SecurityUserContext.getUserId();
//            } catch (Exception e) {
//                userID = Long.valueOf(-1);
//            }

            if (Objects.isNull(baseDO.getCreatedAt())) {
                setFieldValByName(CommonConstant.CREATED_AT, current, metaObject);
            }

            if (Objects.isNull(baseDO.getUpdatedAt())) {
                setFieldValByName(CommonConstant.UPDATED_AT, current, metaObject);
            }
            if (Objects.nonNull(userID) && Objects.isNull(baseDO.getCreatedBy())) {
                setFieldValByName(CommonConstant.CREATE_BY, userID, metaObject);
            }

            if (Objects.nonNull(userID) && Objects.isNull(baseDO.getUpdatedBy())) {
                setFieldValByName(CommonConstant.UPDATE_BY, userID, metaObject);
            }
        }
        if (metaObject.getOriginalObject() instanceof LogicDO) {
            LogicDO baseDO = (LogicDO) metaObject.getOriginalObject();
            if (Objects.isNull(baseDO.getIsDeleted())) {
                setFieldValByName(CommonConstant.IS_DELETED, false, metaObject);
            }
        }


    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.getOriginalObject() instanceof BaseDO) {
            BaseDO baseDO = (BaseDO) metaObject.getOriginalObject();
            Long userID = -1L;

//todo            try {
//                userID = SecurityUserContext.getUserId();
//            } catch (Exception e) {
//                userID = Long.valueOf(-1);
//            }
            Date current = new Date();
            setFieldValByName(CommonConstant.UPDATED_AT, current, metaObject);

            if (Objects.nonNull(userID) && Objects.isNull(baseDO.getUpdatedBy())) {
                setFieldValByName(CommonConstant.UPDATE_BY, userID, metaObject);
            }
        }
    }
}
